﻿using DMS.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DMS.Controllers
{
    [Authorize]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        private readonly BUS.Bus _bus = new BUS.Bus();
        
        public ActionResult Index()
        {
            
            return View();
        }

        public ActionResult Dashboard()
        {
            var obj = _bus.ReturnCategoryTree();
            return View();
        }

        

        #region Categories
        public ActionResult Categories()
        {
            var model = new List<CategoryObject>();
            model = _bus.ReturnCategoryTree();
            return View(model);
        }
        public ActionResult CategoryAdd(int? id)
        {
            var model = new CategoryModel();
            ViewBag.ButtonName = "Thêm mới";
            if(id.HasValue)
            {
                var obj = _bus.Category_Select_by_Id(id.GetValueOrDefault());
                model = new CategoryModel
                {
                    CategoryActive = obj.CategoryActive,
                    CategoryDescription = obj.CategoryDescription,
                    CategoryName = obj.CategoryName,
                    CategoryParentId = obj.CategoryParentId.ToString(),
                    CategoryId = obj.CategoryId
                };
                ViewBag.ButtonName = "Cập nhật";
            }

            model.Categories = _bus.SelectListCategories(0, -1);


            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CategoryAdd(CategoryModel model)
        {
            ViewBag.ButtonName = "Thêm mới";
            if (ModelState.IsValid)
            {
                if (model.CategoryId > 0)
                {
                    _bus.Category_Update(model);
                }
                else
                {
                    _bus.Category_Insert(model);
                }

                return RedirectToAction("categories", "admin");
            }
            else
            {
                ViewBag.ErrorMessage = "Bạn chưa nhập đủ thông tin.";
                model.Categories = _bus.SelectListCategories(0, -1);
                if(model.CategoryId >0)
                {
                    ViewBag.ButtonName = "Cập nhật";
                }
            }
            return View(model);
        }

        #endregion

        #region Documents
        public ActionResult Documents()
        {
            var model = new List<DocumentObject>();
            model = _bus.Document_Select_All();
            return View(model);
        }

        public ActionResult DocumentAdd(int? id)
        {
            ViewBag.ButtonName = "Thêm mới";
            var model = new DocumentModel();
            if(id.HasValue)
            {
                ViewBag.ButtonName = "Cập nhật";
                var obj = _bus.Document_Select_by_Id(id.GetValueOrDefault());
                model = new DocumentModel
                {
                    DocumentCode = obj.DocumentCode,
                    DocumentContent = obj.DocumentContent,
                    DocumentDescription = obj.DocumentDescription,
                    DocumentImage = obj.DocumentImage,
                    DocumentLink = obj.DocumentLink,
                    DocumentName = obj.DocumentName,
                    DocumentType = obj.DocumentType,
                    CategoryOther = obj.CategoryOther,
                    Active = obj.Active,
                    Appoved = obj.Appoved,
                    CategoryId = obj.CategoryId,
                    DocumentId = obj.DocumentId,
                   
                };
            }
            model.DocumentType_List = _bus.SelectList_DocumentType();
            model.Category_List = _bus.SelectListCategories(0, 1);
            return View(model);
        }

        [HttpPost]
        public ActionResult DocumentAdd(DocumentModel model)
        {
            ViewBag.ButtonName = "Thêm mới";
            if(ModelState.IsValid)
            {
                if (model.DocumentId > 0)
                {
                    _bus.Document_Update(model);
                }
                else
                {
                    _bus.Document_Insert(model);
                }
                return RedirectToAction("documents","admin");
            }
            else
            {
                if(model.DocumentId>0)
                {
                    ViewBag.ButtonName = "Cập nhật";
                }
                ViewBag.ErrorMessage = "Bạn chưa điền đủ thông tin.";
            }

            model.DocumentType_List = _bus.SelectList_DocumentType();
            model.Category_List = _bus.SelectListCategories(0, 1);
            return View(model);
        }
        public ActionResult UploadFiles()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(int? catId, int? docType)
        {
            bool isSavedSuccessfully = true;
            string fName = string.Empty;
            string pathString = string.Empty;
            string strDate = DateTime.Now.ToString("yyyy/MM/dd");
            string url = string.Empty;
            string messError = string.Empty;
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {
                        string strFormat = "{0}UploadFiles\\" + docType.GetValueOrDefault() + "\\" + catId.GetValueOrDefault() + "\\" + strDate.Replace("/","\\") + "\\";
                        var originalDirectory = new DirectoryInfo(string.Format(strFormat, Server.MapPath(@"\")));

                        pathString = System.IO.Path.Combine(originalDirectory.ToString());

                        bool isExists = System.IO.Directory.Exists(pathString);

                        if (!isExists)
                            System.IO.Directory.CreateDirectory(pathString);

                        string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + file.FileName.Replace(" ","");
                        url = string.Format(strFormat, "\\") + newFileName;
                        url = url.Replace("\\", "/");
                        var path = string.Format("{0}\\{1}", pathString, newFileName);
                        file.SaveAs(path);

                    }

                }

            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
                messError = ex.Message;
            }


            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName, Url = url });
            }
            else
            {
                return Json(new { Message = messError });
            }
        }

        #endregion

        #region Banners
        public ActionResult Banners()
        {
            var model = new List<BannerObject>();
            model = _bus.Banner_Select();

            return View(model);
        }

        public ActionResult BannerAdd(int? id)
        {
            ViewBag.ButtonName = "Thêm mới";
            var model = new BannerModel();

            if(id.HasValue)
            {
                ViewBag.ButtonName = "Cập nhật";
                model = _bus.Banner_Select_by_Id(id.GetValueOrDefault());
            }

            model.BannerPosition_List = _bus.SelectList_BannerPosition();
            model.BannerType_List = _bus.SelectList_BannerType();

            return View(model);
        }

        [HttpPost]
        public ActionResult BannerAdd(BannerModel model)
        {
            ViewBag.ButtonName = "Thêm mới";
            if(ModelState.IsValid)
            {
                string[] strDate = model.StartEndDate.Split("-".ToCharArray());
                model.StartDate = Convert.ToDateTime(strDate[0]);
                model.EndDate = Convert.ToDateTime(strDate[1]);
                if(model.BannerId>0)
                {
                    ViewBag.ButtonName = "Cập nhật";                    

                    _bus.Banner_Update(model);
                }
                else
                {
                    _bus.Banner_Insert(model);
                }

                return RedirectToAction("banners", "admin");
            }
            else
            {
                ViewBag.ErrorMessage = "Bạn chưa nhập đủ thông tin.";
            }

            model.BannerPosition_List = _bus.SelectList_BannerPosition();
            model.BannerType_List = _bus.SelectList_BannerType();
            return View(model);
        }
        #endregion
    }
}
